﻿using System;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Modular.Domain;
using WeDonekRpc.Modular.Model;

namespace WeDonekRpc.Modular.Accredit
{
    /// <summary>
    /// 默认授权服务
    /// </summary>
    [ClassLifetimeAttr(ClassLifetimeType.SingleInstance)]
    internal class DefAccreditService : AccreditService, IAccreditService, IAccredit
    {
        public override void ClearAccredit ()
        {
            _UserState = null;
            base.ClearAccredit();
        }

        public DefAccreditService ()
        {

        }
        [ThreadStatic]
        private static IUserState _UserState = null;

        private static readonly Type _StateType = typeof(UserState);
        public IUserState CurrentUser => _UserState;


        public IUserState GetAccredit (string accreditId)
        {
            if (_UserState != null && _UserState.AccreditId == accreditId)
            {
                return _UserState;
            }
            UserAccreditDomain accredit = _GetAccredit(accreditId);
            _UserState = accredit.GetUserState(_StateType);
            return _UserState;
        }
        public void CancelAccredit (string accreditId)
        {
            Cancel(accreditId);
        }
        /// <summary>
        /// 设置当前授权并检查授权信息
        /// </summary>
        /// <param name="accreditId"></param>
        /// <returns></returns>
        public IUserState SetCurrentAccredit (string accreditId)
        {
            UserAccreditDomain accredit = base.SetAccredit(accreditId);
            _UserState = accredit.GetUserState(_StateType);
            return _UserState;
        }
    }
}
